import { Injectable, NotFoundException, ForbiddenException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { TaskComment, Task, User } from '../../entities';
import { CreateTaskCommentDto, UpdateTaskCommentDto } from './dto';

@Injectable()
export class TaskCommentService {
  constructor(
    @InjectRepository(TaskComment)
    private taskCommentRepository: Repository<TaskComment>,
    @InjectRepository(Task)
    private taskRepository: Repository<Task>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  /**
   * 创建任务评论
   */
  async createComment(
    createTaskCommentDto: CreateTaskCommentDto, 
    userId: string
  ): Promise<TaskComment> {
    const { content, taskId } = createTaskCommentDto;

    // 检查任务是否存在
    const task = await this.taskRepository.findOne({ 
      where: { id: taskId } 
    });
    if (!task) {
      throw new NotFoundException(`任务 ID ${taskId} 不存在`);
    }

    // 创建新评论
    const comment = this.taskCommentRepository.create({
      content,
      taskId,
      userId,
    });

    return this.taskCommentRepository.save(comment);
  }

  /**
   * 获取任务的所有评论
   */
  async getTaskComments(taskId: string): Promise<TaskComment[]> {
    // 检查任务是否存在
    const task = await this.taskRepository.findOne({ 
      where: { id: taskId } 
    });
    if (!task) {
      throw new NotFoundException(`任务 ID ${taskId} 不存在`);
    }

    return this.taskCommentRepository.find({
      where: { taskId },
      relations: ['user'],
      order: { createdAt: 'DESC' },
    });
  }

  /**
   * 获取评论详情
   */
  async getCommentById(id: string): Promise<TaskComment> {
    const comment = await this.taskCommentRepository.findOne({
      where: { id },
      relations: ['user'],
    });

    if (!comment) {
      throw new NotFoundException(`评论 ID ${id} 不存在`);
    }

    return comment;
  }

  /**
   * 更新评论
   */
  async updateComment(
    id: string, 
    updateTaskCommentDto: UpdateTaskCommentDto, 
    userId: string
  ): Promise<TaskComment> {
    const comment = await this.taskCommentRepository.findOne({
      where: { id },
    });

    if (!comment) {
      throw new NotFoundException(`评论 ID ${id} 不存在`);
    }

    // 只有评论创建者才能更新评论
    if (comment.userId !== userId) {
      throw new ForbiddenException('您没有权限更新此评论');
    }

    // 更新评论内容
    comment.content = updateTaskCommentDto.content;

    return this.taskCommentRepository.save(comment);
  }

  /**
   * 删除评论
   */
  async deleteComment(id: string, userId: string): Promise<void> {
    const comment = await this.taskCommentRepository.findOne({
      where: { id },
    });

    if (!comment) {
      throw new NotFoundException(`评论 ID ${id} 不存在`);
    }

    // 只有评论创建者才能删除评论
    if (comment.userId !== userId) {
      throw new ForbiddenException('您没有权限删除此评论');
    }

    await this.taskCommentRepository.remove(comment);
  }

  /**
   * 清除任务的所有评论（当任务被永久删除时）
   */
  async deleteTaskComments(taskId: string): Promise<void> {
    const comments = await this.taskCommentRepository.find({
      where: { taskId },
    });

    await this.taskCommentRepository.remove(comments);
  }
} 